package com.xiaoxi.bms.common.util;

import com.xiaoxi.bms.common.response.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Author xiaoxi
 * @ProjectName bms
 * @PackageName com.xiaoxi.bms.common.util
 * @ClassName HttpUtils
 * @Description TODO
 * @Date 2023/6/5 11:31
 * @Version 1.0
 */
@Slf4j
public class HttpUtils {

    /**
     * 获取请求body数据
     *
     * @param request
     * @return
     */
    public static String getBodyString(ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try (InputStream inputStream = request.getInputStream()) {
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.warn("getBodyString出现问题！");
        } finally {     // 使用完 流处理 需要关闭
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error(ExceptionUtils.getMessage(e));
                }
            }
        }
        return sb.toString();
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response    渲染对象
     * @param apiResponse 待渲染的 api 请求响应
     */
    public static void renderString(HttpServletResponse response, ApiResponse apiResponse, HttpStatus status) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(ApiResponse.apiResponseToJson(apiResponse));
            response.setStatus(status.value());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("HttpUtil处理异常");
        }
    }
}